package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Friend;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.FriendService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service //dubbo
public class FriendServiceImpl implements FriendService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void addContact(Long userId, Long friendId) {
        //1.我加好友
        //1.1 创建条件对象
        Query query1 = new Query(
                Criteria.where("userId").is(userId)
                .and("friendId").is(friendId)
        );
        //1.2 若之前没有加过,保存记录
        Friend friend1 = mongoTemplate.findOne(query1, Friend.class);
        if (friend1 == null) {
            friend1 = new Friend();
            friend1.setCreated(System.currentTimeMillis());
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);

            mongoTemplate.save(friend1);
        }

        //2.好友加我
        //2.1 创建条件对象
        Query query2 = new Query(
                Criteria.where("userId").is(friendId)
                        .and("friendId").is(userId)
        );
        //2.2 若之前没有加过,保存记录
        Friend friend2 = mongoTemplate.findOne(query2, Friend.class);
        if (friend2 == null) {
            friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);

            mongoTemplate.save(friend2);
        }
    }

    @Override
    public PageBeanVo findContactsByPage(int pageNum, int pageSize, Long userId) {
        //1.创建条件查询对象
        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).skip((pageNum - 1) * pageSize).limit(pageSize);

        //2.查询好友列表
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //3.查询总记录数
        long count = mongoTemplate.count(query, Friend.class);

        //4.封装pageBeanVo  且返回
        return new PageBeanVo(pageNum,pageSize,count,friends);
    }

    @Override
    public boolean isFriend(Long userId, Long friendId) {
        return mongoTemplate.exists(Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId)),Friend.class);
    }

    @Override
    public void deleteContact(Long userId, Long friendId) {
        //相互删除
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId)),Friend.class);
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId)),Friend.class);
    }
}
